<?php

/**
 * 订单分析
 *
 * @author haifeng.wu
 */

require_once 'CommonController.php';
class Admin_OrderAnalyticsController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_DayData();
        $this->dayAreaDataModel = new Application_Model_DayAreaData();
        $this->sourceModel = new Application_Model_Source();
        $this->memberModel = new Application_Model_Member();
        $this->orderModel = new Application_Model_Order();
        $this->view->title = "管理中心";
    }

    /**
     * 默认动作
     * 
     * @return void
     */
    public function listAction()
    {
        $vars = array();
        $wheres = array();
        $vars['dateType']  = trim($this->_request->get('dateType')) ? trim($this->_request->get('dateType')) : 6;
        $vars['doType']    = trim($this->_request->get('doType')) ? trim($this->_request->get('doType')) : 1;
        $vars['startTime'] = trim($this->_request->get('startTime'));
        $vars['endTime']   = trim($this->_request->get('endTime'));
        if ($vars['dateType']==6){
            $vars['startTime'] = date('Y-m-d',strtotime("now"));
            $vars['endTime']   = date('Y-m-d',strtotime("now"));
        } elseif ($vars['dateType']==1){
            $vars['startTime'] = date('Y-m-d',strtotime("-1 day"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==2){
            $vars['startTime'] = date('Y-m-d',strtotime("-8 day"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==3){
            $vars['startTime'] = date('Y-m-d',strtotime("-31 day"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==4){
            $vars['startTime'] = date('Y-m-d',strtotime("-3 months"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==5){
            $vars['startTime'] = '';
            $vars['endTime']   = '';
        }
        $this->view->vars = $vars;
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $wheres[] = "`productCode` = '{$productCode}'";
        
        if ($vars['startTime'] != '') {
            $wheres[] = "`date` >= '{$vars['startTime']}' ";
        }
        if ($vars['endTime'] != '') {
            $wheres[] = "`date` <= '{$vars['endTime']}' ";
        }
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $group = '';
        if ($vars['doType'] == 3) { //操作系统分析
            $sql = "SELECT osname as name,SUM(okOrderAmount) AS amount,SUM(okOrderNum) AS num  FROM " . $this->_model->getTableName() . $where . " 
                    GROUP BY osname
                   ";
            $row = $this->_model->getAdapter()->fetchAll($sql);
            $tmpArray = array();
            $tmpArray = empty($row) ? $tmpArray : sysSortArray($row,'amount',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            $amountTotal = 0;
            $numTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name'])) {
                    $tmpArray[$key]['name'] = '未知';
                }
                $amountTotal += $val['amount'];
                $numTotal += $val['num'];
            }

            //总计数据
            $totalArray = array('amountTotal' => $amountTotal, 'numTotal' => round($numTotal));
            if ($totalArray['amountTotal'] == 0) {
                $totalArray['amountTotalPer'] = '--';
            } else {
                $totalArray['amountTotalPer'] = '100%';
            }
            if ($totalArray['numTotal'] == 0) {
                $totalArray['numTotalPer'] = '--';
            } else {
                $totalArray['numTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal ,4) * 100;
                $tmpArray[$key]['numPer'] = $numTotal == 0 ? 0 :round($val['num']/$numTotal, 4) * 100;
                $tmpArray[$key]['amountOne'] = $val['num'] ==0 ? 0 : number_format($val['amount']/$val['num'], 2);
            }

            //金额占比小于百分之一数据的计算
            $endArray = array('name' => '其他', 'amount' =>0, 'num' => 0, 'amountPer' => 0, 'numPer' => 0, 'amountOne' => '');
            foreach ($tmpArray as $key => $val) {
                if ($val['amountPer'] < 0) {
                    $endArray['amount'] += $val['amount'];
                    $endArray['num'] += $val['num'];
                    $endArray['numPer'] += $val['numPer'];
                    unset($tmpArray[$key]);
                }
            }
            if ($endArray['amount'] != 0) {
                $endArray['amountOne'] = $endArray['num'] ==0 ? 0 : number_format($endArray['amount']/$endArray['num'], 2);
                $endArray['amountPer'] = ($totalArray['amountTotal'] ==0 ? 0 : number_format($endArray['amount']/$totalArray['amountTotal'], 4))*100;
                $tmpArray[] = $endArray;
            }
            $amountOneTotal = 0;
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                $tmpArray[$key]['num'] = round($val['num']);
            }
            $totalArray['amountOne'] = $totalArray['numTotal'] ==0 ? 0 : number_format($totalArray['amountTotal']/$totalArray['numTotal'], 2);
            $totalArray['amountTotal'] = number_format($totalArray['amountTotal'], 2);
            $this->view->totalArray = $totalArray;
            $this->view->tmpArray = $tmpArray;
        }else if($vars['doType'] == 4) {
            $sql = "SELECT province AS `name`,SUM(okOrderAmount) AS amount,SUM(okOrderNum) AS `num` FROM " . $this->dayAreaDataModel->getTableName() . $where . " GROUP BY province";
            $row = $this->_model->getAdapter()->fetchAll($sql);
            $tmpArray = array();
            $tmpArray = empty($row) ? $tmpArray : sysSortArray($row,'amount',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            $amountTotal = 0;
            $numTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name']) || $val['name'] == '其他') {
                    $tmpArray[$key]['name'] = '国外';
                }
                $amountTotal += $val['amount'];
                $numTotal += $val['num'];
            }

            //总计数据
            $totalArray = array('amountTotal' => $amountTotal, 'numTotal' => round($numTotal));
            if ($totalArray['amountTotal'] == 0) {
                $totalArray['amountTotalPer'] = '--';
            } else {
                $totalArray['amountTotalPer'] = '100%';
            }
            if ($totalArray['numTotal'] == 0) {
                $totalArray['numTotalPer'] = '--';
            } else {
                $totalArray['numTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal ,4) * 100;
                $tmpArray[$key]['numPer'] = $numTotal == 0 ? 0 :round($val['num']/$numTotal, 4) * 100;
                $tmpArray[$key]['amountOne'] = $val['num'] ==0 ? 0 : number_format($val['amount']/$val['num'], 2);
                if ($val['amount'] == 0 && $val['num'] == 0) {
                    unset($tmpArray[$key]);
                }
            }

            $amountOneTotal = 0;
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                $tmpArray[$key]['num'] = round($val['num']);
            }
            $totalArray['amountOne'] = $totalArray['numTotal'] ==0 ? 0 : number_format($totalArray['amountTotal']/$totalArray['numTotal'], 2);
            $totalArray['amountTotal'] = number_format($totalArray['amountTotal'], 2);
            $this->view->totalArray = $totalArray;
            $this->view->tmpArray = $tmpArray;
        } else if($vars['doType'] == 2) {//专题
            $this->topictoorderModel = new Application_Model_ActDayDataTopictoorder();
            $sql = "SELECT eventPageName AS `name`,SUM(amount) AS amount,SUM(pv) AS num FROM " . $this->topictoorderModel->getTableName() . $where . " AND `pageId`='1013' GROUP BY eventPageName";
            $row = $this->_model->getAdapter()->fetchAll($sql);
            $tmpArray = array();
            $tmpArray = empty($row) ? $tmpArray : sysSortArray($row,'amount',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            $amountTotal = 0;
            $numTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name'])) {
                    $tmpArray[$key]['name'] = '未知';
                }
                $amountTotal += $val['amount'];
                $numTotal += $val['num'];
            }

            //总计数据
            $totalArray = array('amountTotal' => $amountTotal, 'numTotal' => round($numTotal));
            if ($totalArray['amountTotal'] == 0) {
                $totalArray['amountTotalPer'] = '--';
            } else {
                $totalArray['amountTotalPer'] = '100%';
            }
            if ($totalArray['numTotal'] == 0) {
                $totalArray['numTotalPer'] = '--';
            } else {
                $totalArray['numTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal ,4) * 100;
                $tmpArray[$key]['numPer'] = $numTotal == 0 ? 0 :round($val['num']/$numTotal, 4) * 100;
                $tmpArray[$key]['amountOne'] = $val['num'] ==0 ? 0 : number_format($val['amount']/$val['num'], 2);
            }

            //金额占比小于百分之一数据的计算
            $endArray = array('name' => '其他', 'amount' =>0, 'num' => 0, 'amountPer' => 0, 'numPer' => 0, 'amountOne' => '');
            foreach ($tmpArray as $key => $val) {
                if ($val['amountPer'] < 1) {
                    $endArray['amount'] += $val['amount'];
                    $endArray['num'] += $val['num'];
                    $endArray['numPer'] += $val['numPer'];
                    unset($tmpArray[$key]);
                }
            }
            if ($endArray['amount'] != 0) {
                $endArray['amountOne'] = $endArray['num'] ==0 ? 0 : number_format($endArray['amount']/$endArray['num'], 2);
                $endArray['amountPer'] = ($totalArray['amountTotal'] ==0 ? 0 : number_format($endArray['amount']/$totalArray['amountTotal'], 4))*100;
                $tmpArray[] = $endArray;
            }
            $amountOneTotal = 0;
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                $tmpArray[$key]['num'] = round($val['num']);
            }
            $totalArray['amountOne'] = $totalArray['numTotal'] ==0 ? 0 : number_format($totalArray['amountTotal']/$totalArray['numTotal'], 2);
            $totalArray['amountTotal'] = number_format($totalArray['amountTotal'], 2);
            $this->view->totalArray = $totalArray;
            $this->view->tmpArray = $tmpArray;
        } else {
            $sql = "SELECT `code`,MAX(`name`) AS name,SUM(amount) AS amount,SUM(num) AS num FROM (
                        SELECT sourceAmount.*,sourcemember.name,sourcemember.code FROM 
                        (
                        
                            SELECT productcode,sourceid,sourceSubId,SUM(okOrderAmount) AS amount,SUM(okOrderNum) AS num  FROM " . $this->_model->getTableName() . $where
                             . " GROUP BY productcode,sourceid,sourceSubId
                            
                        ) AS sourceAmount
                        
                        LEFT JOIN
                        (
                            SELECT `name`,`code`,productcode,sourceid,sourcesubid FROM " . $this->sourceModel->getTableName() . " LEFT JOIN `mob_member` ON mob_source.`memberCode`=`mob_member`.`code` 
                            WHERE productcode='" . $productCode . "'
                        ) sourcemember 
                        ON sourceAmount.productcode=sourcemember.productcode AND sourceAmount.sourceid=sourcemember.sourceid 
                        AND sourceAmount.sourcesubid=sourcemember.sourcesubid
                    )aaa GROUP BY `code` ";
            $row = $this->_model->getAdapter()->fetchAll($sql);
            $tmpArray = array();
            $tmpArray = empty($row) ? $tmpArray : sysSortArray($row,'amount',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            $amountTotal = 0;
            $numTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name'])) {
                    $tmpArray[$key]['name'] = '未知';
                }
                $amountTotal += $val['amount'];
                $numTotal += $val['num'];
            }

            //总计数据
            $totalArray = array('amountTotal' => $amountTotal, 'numTotal' => round($numTotal));
            if ($totalArray['amountTotal'] == 0) {
                $totalArray['amountTotalPer'] = '--';
            } else {
                $totalArray['amountTotalPer'] = '100%';
            }
            if ($totalArray['numTotal'] == 0) {
                $totalArray['numTotalPer'] = '--';
            } else {
                $totalArray['numTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal ,4) * 100;
                $tmpArray[$key]['numPer'] = $numTotal == 0 ? 0 :round($val['num']/$numTotal, 4) * 100;
                $tmpArray[$key]['amountOne'] = $val['num'] ==0 ? 0 : number_format($val['amount']/$val['num'], 2);
            }

            //金额占比小于百分之一数据的计算
            $endArray = array('code'=>'other', 'name' => '其他', 'amount' =>0, 'num' => 0, 'amountPer' => 0, 'numPer' => 0, 'amountOne' => '', 'strCode' => '');
            $arrayCode = array();
            foreach ($tmpArray as $key => $val) {
                if ($val['amountPer'] < 0) {
                    $endArray['amount'] += $val['amount'];
                    $endArray['num'] += $val['num'];
                    $endArray['numPer'] += $val['numPer'];
                    $arrayCode[] = $val['code'];
                    unset($tmpArray[$key]);
                }
            }
            if ($endArray['amount'] != 0) {
                $endArray['amountOne'] = $endArray['num'] ==0 ? 0 : number_format($endArray['amount']/$endArray['num'], 2);
                $endArray['amountPer'] = ($totalArray['amountTotal'] ==0 ? 0 : number_format($endArray['amount']/$totalArray['amountTotal'], 4))*100;
                $endArray['strCode'] = implode(',', $arrayCode);
                $tmpArray[] = $endArray;
            }
            $amountOneTotal = 0;
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                $tmpArray[$key]['num'] = round($val['num']);
            }
            $totalArray['amountOne'] = $totalArray['numTotal'] ==0 ? 0 : number_format($totalArray['amountTotal']/$totalArray['numTotal'], 2);
            $totalArray['amountTotal'] = number_format($totalArray['amountTotal'], 2);
            $this->view->totalArray = $totalArray;
            $this->view->tmpArray = $tmpArray;
        }
    }

    
    /**
    * 获取软件包
    * @return void
    */
    function getSourceNameListAction(){
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $name = trim($this->_request->getPost('name'));
        $startTime = trim($this->_request->getPost('startTime'));
        $strCode = trim($this->_request->getPost('strCode'));
        if (empty($startTime)) {
            $startTime = 0;
        }
        $endTime = trim($this->_request->getPost('endTime'));
        if (empty($endTime)) {
            $endTime = date('Y-m-d');
        }
        if (!empty($strCode)) {
            $tmpCode = array();
            $tmpCode = explode(',', $strCode);
            $type = 1;
            if (in_array('', $tmpCode)) {
                $type = 0;
            }
            $strCode = "'" . str_replace(",", "','", $strCode) . "'";
            $where = '';
            if ($type == 1) {
                $where .= " c.code in (" . $strCode . ") ";
            } else {
                $where .= " ( c.code in (" . $strCode . ") or c.name IS NULL )";
            }
        } else {
            $where = '';
            if ($name == '未知') {
                $where .= " c.name IS NULL ";
            } else {
                $where .= " c.name = '{$name}' ";
            }

        }
        
        $sql = "SELECT sourceid,sourceSubId,`name`,SUM(amount) AS amount,SUM(num) AS num FROM (
                    SELECT sourceAmount.*,sourceNa.sourceName as `name` FROM 
                    (
                    
                        SELECT productcode,sourceid,sourceSubId,SUM(okOrderAmount) AS amount,SUM(okOrderNum) AS num  
                        FROM mob_day_data
                        WHERE `date`>='{$startTime}' AND `date`<='{$endTime}' and `productcode`='{$productCode}' 
                        GROUP BY productcode,sourceid,sourceSubId
                        
                    ) AS sourceAmount
                    
                    LEFT JOIN
                    (
                        SELECT `sourceName`,productcode,sourceid,sourcesubid,memberCode 
                        FROM mob_source 
                        WHERE productcode='{$productCode}'
                    ) sourceNa 
                    ON sourceAmount.productcode=sourceNa.productcode AND sourceAmount.sourceid=sourceNa.sourceid 
                    AND sourceAmount.sourcesubid=sourceNa.sourcesubid
                    
                    LEFT JOIN mob_member as c 
                    ON sourceNa.memberCode = c.code
                    WHERE {$where}
                )c 
                WHERE num != 0
                GROUP BY sourceid,sourceSubId
                ORDER BY amount DESC";
        $row = $this->_model->getAdapter()->fetchAll($sql);
        $amountTotal = 0;
        $numTotal = 0;

        foreach ($row as $key => $val) {
            $numTotal += $val['num'];
            $amountTotal += $val['amount'];
        }
        //计算占比
        foreach ($row as $key => $val) {
                $row[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal ,4) * 100;
                $row[$key]['numPer'] = $numTotal == 0 ? 0 :round($val['num']/$numTotal, 4) * 100;
                $row[$key]['amountOne'] = $val['num'] ==0 ? 0 : number_format($val['amount']/$val['num'], 2);
        }
        $table = '<tr class="subject">
                    <td>子渠道</td>
                    <td colspan="2">订单</td>
                    <td colspan="2">订单量</td>
                    <td>客单价(￥)</td>
                  </tr>
                  <tr class="subject">
                    <td>名称</td>
                    <td>金额(￥)</td>
                    <td>占比(%)</td>
                    <td>数量</td>
                    <td>占比(%)</td>
                    <td></td>
                  </tr>';
        foreach ($row as $item) {
            $table .= '
                      <tr>
                        <td>' . $item["name"] . '</td>
                        <td>' . $item["amount"] . '</td>
                        <td>' . $item["amountPer"] . '</td>
                        <td>' . $item["num"] . '</td>
                        <td>' . $item["numPer"] . '</td>
                        <td>' . $item["amountOne"] . '</td>
                      </tr>
            ';
        }
        echo json_encode(array('table' => $table));
        exit;
    }
    
}